//
//  HBRefreshView.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/29.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

enum HBRefreshType: Int {
    case Normal = 0
    case Pulling = 1
    case Loading = 2
}

class HBRefreshView: UIControl {

    // 定义属性, 来记录状态
    var type: HBRefreshType = .Normal {
        didSet {
            // 在didSet中实现效果
            switch type {
            case .Normal:
                printLog("正常状态")
                msgLbl.text = "下拉刷新"
                arrowImgView.hidden = false
                loadingView.stopAnimating()
                // 箭头恢复
                self.arrowImgView.transform = CGAffineTransformIdentity

            case .Pulling:
                printLog("拖拽状态")
                msgLbl.text = "释放更新"
                // 箭头转半圈
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImgView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })

            case .Loading:
                printLog("加载状态")
                msgLbl.text = "加载中..."
                arrowImgView.hidden = true
                loadingView.startAnimating()

                // 让视图停留一下
                var inset = scrollView!.contentInset
                inset.top = inset.top + self.bounds.height
                scrollView?.contentInset = inset

                // 加载数据 -- 回调
                // 利用control的父类方法去调用ValueChanged方法
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }

    // 定义为属性
    var scrollView: UIScrollView?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = UIColor.greenColor()

        // 设置默认的宽高
        var frame = self.frame
        frame.size = CGSizeMake(kScreenWidth, 50)
        frame.origin.y = -50
        self.frame = frame

        addSubview(arrowImgView)
        addSubview(msgLbl)
        addSubview(loadingView)

        arrowImgView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        msgLbl.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowImgView.snp_right).offset(HomeCellMargin)
            make.centerY.equalTo(self)
        }
        loadingView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
    }

    // 在控件将要添加到父控件时执行
    override func willMoveToSuperview(newSuperview: UIView?) {
        printLog(newSuperview)

        // 可以把抽取的下拉刷新扩展到UIScrollView
        if newSuperview is UIScrollView {
            scrollView = newSuperview as? UIScrollView
            // 添加KVO监听方法
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }

    // MARK: - 监听者需要实现属性的监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        printLog(scrollView?.contentOffset.y)

        if scrollView!.dragging {   // 拖拽着
            if scrollView?.contentOffset.y < -140 && type == .Normal {
                printLog("状态改变, '释放更新'")
                // 记录状态
                type = .Pulling
            } else if scrollView?.contentOffset.y >= -140 && type == .Pulling {
                printLog("状态改变, '下拉刷新'")
                type = .Normal
        }

        // 当满足释放更新(.Pulling), 松手去加载数据
        } else {    // 松手
            // 判断加载的前提条件
            if scrollView?.contentOffset.y < -140 && type == .Pulling {
                printLog("改变状态, '加载中'")
                type = .Loading
            }
        }
    }

    // MARK: - 防系统下拉完成方法
    func endRefreshing() {
        // 问题: 当没有判断标记时, 第一次网络请求之后会执行这个操作. 应该加载后才能调用
        if type == .Loading {
            var inset = scrollView!.contentInset
            inset.top = inset.top - self.bounds.height
            scrollView?.contentInset = inset
        }

        // 改变一下状态
        type = .Normal
    }

    // MARK: - lazy load
    // 箭头
    private lazy var arrowImgView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "tableview_pull_refresh")
        return imgView
    }()
    // 提示语
    private lazy var msgLbl: UILabel = UILabel(text: "下拉刷新", fontSize: 15.0, textColor: UIColor.darkGrayColor(), isSingleLine: true)
    // 菊花
    private lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
}
